import Context from '../context';
import { useMemoizedFn } from 'ahooks';
import { useEffect, useContext } from 'react';
import type { EventType } from '@svgedit/svgcanvas';

export type EventListener = (
  eles: Element[],
  mode: string
) => void;

function useEvent(type: EventType, listener: EventListener) {
  const { editor } = useContext(Context);
  const bindEvt = useMemoizedFn(() => (
    editor.bindEvent(type, (_, eles) => {
      listener(eles, editor.getMode());
    })
  ));
  useEffect(bindEvt, [type, editor, bindEvt]);
}

export default useEvent;